package com.athl.netty.netty.codec2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Random;

/**
 * @author hl
 * @Data 2020/8/31
 */
public class CoderClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当通道就绪时 触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int random = new Random().nextInt(3);
        MyDataPOJO.MyMessage message = null;
        if (0 == random) { //发送Student
            message = MyDataPOJO.MyMessage.newBuilder().setDataType(MyDataPOJO.MyMessage.DataType.studentType)
                    .setStudent(MyDataPOJO.Student.newBuilder().setId(5).setName("小红").build()).build();
        } else {
            // 发送一个worker对象
            message = MyDataPOJO.MyMessage.newBuilder().setDataType(MyDataPOJO.MyMessage.DataType.workerType)
                    .setWorker(MyDataPOJO.Worker.newBuilder().setAge(15).setName("小张").build()).build();
        }
        ctx.writeAndFlush(message);
        System.out.println("发送消息了");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
    }

    /**
     * 异常发生后
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
